package services

import (
	"sen-golang-study/go_game_study/hero_story_go_server/common"
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/infrastructure/discovery"
	"strings"
)

type DiscoveryService struct {
	etcdDiscovery  *discovery.EtcdDiscovery
	gatewayService *GatewayService
}

func NewDiscoveryService(etcdEndpoints string, gatewayService *GatewayService) *DiscoveryService {
	endpoints := strings.Split(etcdEndpoints, ",")
	for i, endpoint := range endpoints {
		endpoints[i] = strings.TrimSpace(endpoint)
	}

	etcdDiscovery := discovery.NewEtcdDiscovery(endpoints)
	if etcdDiscovery == nil {
		return nil
	}

	ds := &DiscoveryService{
		etcdDiscovery:  etcdDiscovery,
		gatewayService: gatewayService,
	}

	// 设置回调函数
	etcdDiscovery.SetCallbacks(
		ds.onServerAdd,
		ds.onServerRemove,
	)

	return ds
}

func (ds *DiscoveryService) StartDiscovery() {
	go ds.etcdDiscovery.StartWatch()
}

func (ds *DiscoveryService) onServerAdd(serverInfo *common.GameServerInfo) {
	ds.gatewayService.ConnectToGameServer(serverInfo)
}

func (ds *DiscoveryService) onServerRemove(serverID uint32) {
	ds.gatewayService.RemoveGameServer(serverID)
}
